﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using NCS.Library;
using NCS.Library.Components.Roles;
using NCS.Library.Components.Security;
using NCS.Library.Components.Users;
using NCS.Library.Utilities;

namespace Portal.Administrator.Roles
{
	public partial class RoleManagement : AuthenticatedControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            if(!IsPostBack)
            {
                dropRoleParentID.Items.Clear();
                RoleController.LoadRoles(dropRoleParentID.Items);
                dropRoleParentID.Items.Insert(0, new ListItem("Root", "0"));

                DataTable dtUsers;
                if (!CurrentUser.IsAdmin && !CurrentUser.IsSuperAdmin)
                {
                    dtUsers = UserController.GetUsersByUser("", "", "", CurrentUser.UserID, ConvertUtility.ToInt32(AppEnv.PortalId()), 1);
                }
                else
                {
                    dtUsers = UserController.GetUsers("", "", "", ConvertUtility.ToInt32(AppEnv.PortalId()), 1);
                }
                dropUserManager.DataSource = dtUsers;
                dropUserManager.DataBind();
            }
		}
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
		    
            DataTable dtRebuildData = new DataTable();

            dtRebuildData.Columns.Add("RoleID", typeof(String));
            dtRebuildData.Columns.Add("RoleName", typeof(String));
            dtRebuildData.Columns.Add("RoleDescription", typeof(String));
            dtRebuildData.Columns.Add("RoleParentID", typeof(String));
            dtRebuildData.Columns.Add("Level", typeof(String));

            DataTable dtRole;
            if (!CurrentUser.IsAdmin && !CurrentUser.IsSuperAdmin)
            {
                dtRole = RoleController.GetRolesByUserManager(CurrentUser.UserID);
                dtgRoles.DataSource = RoleController.GetRoleByParentIDForUser(dtRole, dtRebuildData);
                dtgRoles.DataBind();
            }
            else
            {
                dtRole = RoleController.GetRoles();
                dtgRoles.DataSource = RoleController.GetRoleByParentID(dtRole,dtRebuildData);
                dtgRoles.DataBind();
            }
		  
		}
		protected void dtgRoles_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			int roleId;
			switch (e.CommandName)
			{
				case "editrole":
					roleId = ConvertUtility.ToInt32(e.CommandArgument);
					RoleInfo role = RoleController.GetRole(roleId);
					txtRoleID.Text = role.RoleID.ToString();
					txtRoleName.Text = role.RoleName;
					txtRoleDescription.Text = role.RoleDescription;
                    txtAddress.Text = role.Address;
                    txtPhone.Text = role.Phone;
                    txtFax.Text = role.Fax;
                    txtEmail.Text = role.Email;
                    try
                    {
                        dropUserManager.SelectedValue = role.UserManager.ToString();
                    }
                    catch {
                        dropUserManager.SelectedIndex = 0;
                    }
                    dropRoleParentID.SelectedValue = role.RoleParentID.ToString();
                    if (roleId == 34) this.btnDelete.Visible = false; else this.btnDelete.Visible = true;
					break;
				case "deleterole":
					try
					{
						roleId = ConvertUtility.ToInt32(e.CommandArgument);
						RoleController.DeleteRole(roleId);
                        lblUpdate.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                        this.AddLog("Role", " try delete role id "+ roleId +" success");
					}
					catch (Exception ex)
					{
						//Response.Write(ex.Message);
                        //Response.Write("Không thể xóa nhóm quyền này vì có người dùng trong nhóm!");
                        lblUpdate.Text = "Không thể xóa nhóm quyền này vì có người dùng trong nhóm!";
                        this.AddLog("Role", " try delete role id " + e.CommandArgument + " error: " + ex.Message);
					}
					break;
				case "rolepermision":
					roleId = ConvertUtility.ToInt32(e.CommandArgument);
                    Response.Redirect(AppEnv.AdminUrlParams("rolepermision") + "&roleid=" + roleId);
					break;
				case "userinrole":
					roleId = ConvertUtility.ToInt32(e.CommandArgument);
					Response.Redirect(AppEnv.AdminUrlParams("userinrole") + "&roleid=" + roleId);
					break;
				default:
					break;
			}
		}
		protected void dtgRoles_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
                NCS.WebControls.ButtonRoleDelete btnDeleteRole = (NCS.WebControls.ButtonRoleDelete)e.Row.FindControl("btnDeleteRole");
                if (btnDeleteRole.CommandArgument == "34")
                {
                    //Role mac dinh => ko xoa
                    btnDeleteRole.Visible = false;

                    Button btnUserInRole = (Button)e.Row.FindControl("btnUserInRole");
                    btnUserInRole.Visible = false;
                }
                
                btnDeleteRole.Attributes.Add("onclick", MiscUtility.MSG_DELETE_CONFIRM);

                if (e.Row.Cells[0].Text == "Default")
                {
                    if (!CurrentUser.IsSuperAdmin)
                    {
                        e.Row.Visible = false;
                    }
                    else
                    {
                        e.Row.Visible = true;
                    }
                }
			}
		}
		protected void btnUpdate_Click(object sender, EventArgs e)
		{
			try
			{
                if (!string.IsNullOrEmpty(txtRoleID.Text))
                {
                    int roleId = ConvertUtility.ToInt32(txtRoleID.Text);
                    RoleInfo role = RoleController.GetRole(roleId);
                    role.RoleName = txtRoleName.Text;
                    role.RoleDescription = txtRoleDescription.Text;
                    role.Address = txtAddress.Text;
                    role.Phone = txtPhone.Text;
                    role.Fax = txtFax.Text;
                    role.Email = txtEmail.Text;
                    role.UserManager = ConvertUtility.ToInt32(dropUserManager.SelectedValue);
                    role.RoleParentID = ConvertUtility.ToInt32(dropRoleParentID.SelectedValue);

                    RoleController.UpdateRole(role);
                    lblUpdate.Text = MiscUtility.MSG_UPDATE_SUCCESS;

                    this.AddLog("Role", " try update role " + txtRoleName.Text + " success");
                }
                else
                {
                    lblUpdate.Text = "Chưa chọn nhóm quyền cần sửa";
                }
			}
			catch (Exception ex)
			{
				Response.Write(ex.Message);
                this.AddLog("Role", " try update role " + txtRoleName.Text + " error: " + ex.Message);
			}
            btnCancel_Click(null, null);
		}
		protected void btnAdd_Click(object sender, EventArgs e)
		{
			try
			{
                if (string.IsNullOrEmpty(txtRoleName.Text.Trim()))
                {
                    lblUpdate.Text = "Hãy nhập tên nhóm quyền";
                    this.txtRoleName.Focus();
                    return;
                }
				RoleInfo role = new RoleInfo();
				role.RoleName = txtRoleName.Text;
				role.RoleDescription = txtRoleDescription.Text;
                role.Address = txtAddress.Text;
                role.Phone = txtPhone.Text;
                role.Fax = txtFax.Text;
                role.Email = txtEmail.Text;
                role.UserManager = ConvertUtility.ToInt32(dropUserManager.SelectedValue);
                role.RoleParentID = ConvertUtility.ToInt32(dropRoleParentID.SelectedValue);
				RoleController.AddRole(role);
                lblUpdate.Text = MiscUtility.MSG_UPDATE_SUCCESS;

                this.AddLog("Role", " try add role " + txtRoleName.Text + " success");
			}
			catch (Exception ex)
			{
				Response.Write(ex.Message);
                this.AddLog("Role", " try add role " + txtRoleName.Text + " error: " + ex.Message);
			}
            btnCancel_Click(null, null);
		}
		protected void btnDelete_Click(object sender, EventArgs e)
		{
			try
			{
                if (!string.IsNullOrEmpty(txtRoleID.Text))
                {
                    int roleId = ConvertUtility.ToInt32(txtRoleID.Text);
                    RoleController.DeleteRole(roleId);
                    lblUpdate.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                    this.AddLog("Role", " try delete role " + txtRoleName.Text + " success");
                }
                else
                {
                    lblUpdate.Text = "Chưa chọn nhóm quyền cần xóa";
                }
			}
			catch (Exception ex)
			{
				Response.Write(ex.Message);
                this.AddLog("Role", " try delete role " + txtRoleName.Text + " error: " + ex.Message);
			}
            btnCancel_Click(null, null);
		}

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            txtRoleID.Text = "";
            txtRoleName.Text = "";
            txtRoleDescription.Text = "";
            txtAddress.Text = "";
            txtPhone.Text = "";
            txtFax.Text = "";
            txtEmail.Text = "";
            dropUserManager.SelectedIndex = -1;
            dropRoleParentID.SelectedIndex = -1;
            lblUpdate.Text = "";
        }

	}
}